const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mytest',{useUnifiedTopology: true,useNewUrlParser: true})
  .then(()=> console.log('链接成功'))
  .catch(err => console.log(err,'链接失败'))

const postSchema = new mongoose.Schema({
  title:{
    type: String,
    required: [true,'plz print'],
    minlength: [2, 'min = 2'],
    maxlength: [5, 'max = 5'],
    trim: true
  },
  age:{
    type: Number,
    min: 18,
    max: 100
  },
  publishDate: {
    type: Date,
    default: Date.now
  },
  category: {
    type: String,
    // 枚举，只能选当前字段里的字符去提交
    enum: ['html','css','javascript','node']
  },
  author: {
    type: String,
    validate: {
      validator: v => {
        return v && v.length > 4
      },
      // 自定义错误信息
      message: '传入的值不符合'
    }
  }
});

const Post = mongoose.model('Post',postSchema);
Post.create({title: 'aa',age: 60, category:'html', author: 'luogege'}).then(res=>{
  console.log(res);
})

